package com.wh.stressservice.service.impl;

import com.wh.stressservice.service.IProcessService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Author xu
 * @Date 2025/2/10
 **/
@Slf4j
@Service
public class ProcessServiceImpl implements IProcessService {

    @Value("${spring.access.startProcess}")
    private String startProcess;

    @Value("${spring.access.processName}")
    private String processName;

    @Value("${spring.access.path}")
    private String path;

    @Value("${spring.access.newPath}")
    private String newPath;

    @Override
    public void startProcess() {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(startProcess);
            processBuilder.start();
            log.info("已启动进程 {}", processName);
        } catch (Exception e) {
            log.error("启动进程时发生错误", e);
        }
    }

    @Override
    public void stopProcess() {
        try {
            Runtime.getRuntime().exec("taskkill /F /IM " + processName);
            log.info("已停止进程 {}", processName);
        } catch (Exception e) {
            log.error("停止进程时发生错误", e);
        }
    }

    @Override
    public boolean isRunning() {
        try {
            Process process = Runtime.getRuntime().exec("tasklist /FI \"IMAGENAME eq " + processName + "\"");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains(processName)) {
                    log.info("进程 {} 正在运行", processName);
                    return true;
                }
            }
        } catch (Exception e) {
            log.error("检查进程状态时发生错误", e);
        }
        log.info("进程 {} 未运行", processName);
        return false;
    }

    @Override
    public void backDbFile() {
        try {
            File sourceFile = new File(path);
            if (sourceFile.exists()) {
                File targetFile = new File(newPath);
                FileUtils.copyFile(sourceFile, targetFile);
                log.info("执行数据库文件备份成功");
                return;
            }
            log.warn("源文件不存在，备份失败");
        } catch (IOException e) {
            log.error("数据库文件备份失败", e);
        }
    }

}
